<?php
// +----------------------------------------------------------------------
// | RXThinkCMF_EVTP5.1_PRO前后端分离旗舰版框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2021 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | 作者: ZhangXuanNeng <rxthinkcmf@163.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;


use app\admin\model\BoxAdStatistics;
use app\admin\model\Member;
use app\admin\model\UserPromote;
use app\api\model\OrderLog;
use app\api\model\RegisterLog;
use app\common\controller\Export;
use think\Db;

/**
 * 媒体管理-服务类
 * @author ZhangXuanNeng
 * @since: 2023/09/08
 * Class BoxAdService
 * @package app\admin\service
 */
class BoxAdStatisticsService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new BoxAdStatistics();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2023/09/08
     * @author ZhangXuanNeng
     */
    public function getList(): array
    {
        $param = request()->param();

        // 查询条件
        $map = [];
        if(!empty($param['time_range'])){
            $map[] = ['day_time','>=',str_replace('-','', $param['time_range'][0])];
            $map[] = ['day_time','<=',str_replace('-','',$param['time_range'][1])];
        }

        // 媒体名称
        $meida = isset($param['mediaid']) ? trim($param['mediaid']) : '';
        if ($meida) {
            $map[] = ['delivery_channel', '=', $meida];
        }
        // 投放产品名称
        $name = isset($param['name']) ? trim($param['name']) : '';
        if ($name) {
            $map[] = ['name', 'like', "%{$name}%"];
        }
        // 产品类型
        $type = isset($param['product_type']) ? trim($param['product_type']) : '';
        if ($type) {
            $map[] = ['product_type', '=', $type];
        }
        // 广告
        $adid = isset($param['adid']) ? trim($param['adid']) : '';
        if ($adid) {
            $map[] = ['adid', '=', $adid];
        }


//        $list = $this->model->where($map)->order('id', 'desc')->page(PAGE, PERPAGE)->select();
        $list = $this->model->where($map)->order('id', 'desc')->page(PAGE, PERPAGE)->select()->toArray();
        array_walk($list, function (&$v) {
            $v['day_time'] = date('Y-m-d', strtotime($v['day_time']));
            $v['ad_name']  = UserPromote::where('id',$v['adid'])->value('nickname') ?? $v['ad_name'];
        });

//        foreach ($list as &$item){
//            $item['day_time'] =  substr_replace($item['day_time'], '-', 4, 0);
//            $item['day_time'] =  substr_replace($item['day_time'], '-', 7, 0);
//            $today = strtotime($item['day_time'] . ' 00:00:00');
//            // 获取当天注册的历史付费人数
//            $where = [
//                ['promote_id', '=', $item['adid']],
//                ['register_time','between', [$today, $today + 86400]]
//            ];
//            $result = (new OrderLog())->field('COUNT(DISTINCT member_id) as pay_total_people_num,SUM(pay_amount) as user_pay_amount')->where($where)->find();
//            $item['pay_total_people_num'] = $result['pay_total_people_num'];
//            $item['user_pay_amount'] = $result['user_pay_amount'];
//            $item['pay_subscriber_rate'] = $item['pay_total_people_num'] ? round($item['pay_total_people_num'] / $item['register_num'] * 100, 2) : 0;
//        }

        //获取数据总数
        $count = $this->model->where($map)->count();

        //返回结果
        return array(
            "msg"   => '操作成功',
            "code"  => 0,
            "data"  => $list,
            "count" => $count,
        );
    }

    public function getAdList(): array
    {
        $where = ['type'=>1,'status'=>1];
        $arr = (new UserPromote())->field('id,nickname')->where($where)->page(PAGE, PERPAGE)->order('id desc')->select();
        $count = (new UserPromote())->where($where)->count();
        //返回结果
        return  array(
            "msg"   => '操作成功',
            "code"  => 0,
            "data"  => $arr,
            "count" => $count,
        );
    }

    public function export()
    {
        $param = request()->param();
        $map = [];
        if(!empty($param['time_range'])){
            $map[] = ['day_time','>=',str_replace('-','', $param['time_range'][0])];
            $map[] = ['day_time','<=',str_replace('-','',$param['time_range'][1])];
        }
        // 媒体名称
        $meida = isset($param['mediaid']) ? trim($param['mediaid']) : '';
        if ($meida) {
            $map[] = ['delivery_channel', '=', $meida];
        }
        // 投放产品名称
        $name = isset($param['name']) ? trim($param['name']) : '';
        if ($name) {
            $map[] = ['name', 'like', "%{$name}%"];
        }
        // 产品类型
        $type = isset($param['product_type']) ? trim($param['product_type']) : '';
        if ($type) {
            $map[] = ['product_type', '=', $type];
        }
        // 广告
        $adid = isset($param['adid']) ? trim($param['adid']) : '';
        if ($adid) {
            $map[] = ['adid', '=', $adid];
        }
        $Export = new Export();
        $Export->boxAdStatistics($map);
    }

    public function getRegisterList($param): array
    {
        $map = [];
        $adid = isset($param['adid']) ? trim($param['adid']) : '';
        if (!$adid) {
            return [
                'msg' => '广告ID不能为空',
                'code' => 1,
            ];
        }
        $member_id = isset($param['member_id']) ? trim($param['member_id']) : '';
        if ($member_id) {
            $map[] = ['member_id', '=', $member_id];
        }
        $nickname = isset($param['nickname']) ? trim($param['nickname']) : '';
        if ($nickname) {
            $where[] = ['nickname', 'like', "%{$nickname}%"];
            $memberList = (new Member())->field('id')->where($where)->select()->toArray();
            $member_ids = array_column($memberList, 'id');
            $map[] = ['member_id', 'in', $member_ids];
        }

        $day_time = $param['day_time'];
        $original_date = substr($day_time, 0, 4) . '-' . substr($day_time, 5, 2) . '-' . substr($day_time, 8);
        $map[] = ['promote_id', '=', $adid];
        $map[] = ['type', '=', 1];
        $map[] = ['is_box', '=', 1];
        $map[] = ['register_time', '>=', strtotime($original_date . ' 00:00:00')];
        $map[] = ['register_time', '<=', strtotime($original_date . ' 23:59:59')];
        $list = (new RegisterLog())
            ->field('member_id,promote_account,device,imei,idfa,androidid,oaid,register_time')
            ->where($map)
            ->order('id', 'desc')
            ->page(PAGE, PERPAGE)
            ->select();

        foreach ($list as $key => $value){
            $list[$key]['nickname'] = (new Member())->where(['id'=>$value['member_id']])->value('nickname');
        }
        $count = (new RegisterLog())->where($map)->count();
        return [
            'msg' => '操作成功',
            'code' => 0,
            'data' => $list->toArray(),
            "count" => $count,
        ];
    }
}
